import axios from 'axios'
import qs from 'qs'
// import Bus from './bus'
// var apiUrl = 'http://zhishuapi.aldwx.com'
var apiUrl = 'http://onlinetestapi.aldzs.com'
// var apiUrl = '/api'

axios.interceptors.request.use(config => {
    return config
}, error => {
    return Promise.reject(error)
})

axios.interceptors.response.use(response => {
    return response
}, error => {
    return Promise.resolve(error.response)
})

function post (url, data, callback, status) {

    return axios({
        method: 'post',
        baseURL: apiUrl,
        url,
        data: qs.stringify(data),
        timeout: 30000,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    }).then(
        (response) => {
            if (response.data && response.data.code === 201) {
                delCookie('zhusername')
                delCookie('phone')
                delCookie('uid')
                // Bus.$emit('getTarget', {type: 'login'})
            }
            callback(checkStatus(response))
        }
    )
}

function checkStatus (response) {
    if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
        return response.data
    } else {
        return {
            code: 202,
            data:[],
            msg: '系统内部错误，请稍后尝试',
            author: 'Youmeng'
        }
    }
}

/* setCookie */

function setCookie (cname, cvalue, exHours) {
    var d = new Date();
    d.setTime(d.getTime() + (exHours * 60 * 60 * 1000));
    var expires = 'expires=' + d.toUTCString();
    console.info(cname + '=' + cvalue + '; ' + expires);
    document.cookie = cname + '=' + cvalue + '; ' + expires;
};

/* getCookie */
function getCookie (cName) {
    if (window.document.cookie.length > 0) {
        let cStart = window.document.cookie.indexOf(cName + '=')
        if (cStart !== -1) {
            cStart = cStart + cName.length + 1
            let cEnd = window.document.cookie.indexOf(';', cStart)
            if (cEnd === -1) {
                cEnd = window.document.cookie.length
            }
            return unescape(window.document.cookie.substring(cStart, cEnd))
        }
    }
    return ''
}

function delCookie (cName) {
    setCookie(cName, '', -1)
}

//  获取 Url 参数
function getQueryString (name) {
    var reg = new RegExp(name + '=([^&]*)(&|$)', 'i')
    var r = window.location.href.match(reg)
    return r != null ? unescape(r[1]) : null
}

function lineTip (ag) {
    var len = ag.length
    var div = '<div class="lineTip">'
    div += '<h5>' + ag[0]['name'] + '</h5>'
    for (var i = 0; i < len; i++) {
        if (ag[i]['seriesName'] === '次均停留时长') {
            div += '<p>' + ag[i]['marker'] + ag[i]['seriesName'] + '<b style="position:absolute; right: 10px">' + ag[i]['data'] + '秒' + '</b>' + '</p >'
        } else if (ag[i]['seriesName'] === '跳出率' || ag[i]['seriesName'] === '新增用户留存' || ag[i]['seriesName'] === '活跃用户留存' || ag[i]['seriesName'] === '日活/周活' || ag[i]['seriesName'] === '日活/月活' || ag[i]['seriesName'] === '分享回流比' || ag[i]['seriesName'] === '错误率') {
            div += '<p>' + ag[i]['marker'] + ag[i]['seriesName'] + '<b style="position:absolute; right: 10px">' + ag[i]['data'] + '%' + '</b>' + '</p >'
        } else {
            div += '<p>' + ag[i]['marker'] + ag[i]['seriesName'] + '<b style="position:absolute; right: 10px">' + ag[i]['data'] + '</b>' + '</p >'
        }
    }
    div += '</div>'
    return div
}

// 判断百度推广
var is_baidu = function () {
    var wdurl = window.location.search
    var aParams = document.location.search.substr(1).split('&')
    var reg = /source/g
    if (reg.test(wdurl)) {
        setCookie('baidut', wdurl, 2)
    }
}

// name  参数为 baidut
var geturlparam = function (name) {
    if (document.cookie.length > 0) {
        if (document.cookie.indexOf(name + '=') >= 0) {
            var arr, reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
            if (arr = document.cookie.match(reg)) {
                // 调用paramfactory 得到一个对象
                return paramfactory(unescape(arr[2]))
            } else {
                return null
            }
        }
    }
}
var paramfactory = function (url) {
    var theRequest = {}
    if (url.indexOf('?') !== -1) {
        let str = url.substr(url.indexOf('?') + 1)
        let strs = str.split('&')
        for (let i = 0; i < strs.length; i++) {
            theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
        }
    }
    return theRequest
}

var baiduPoint = function (eventCategory, eventName) {
    // 百度事件埋点
    window._hmt.push(['_trackEvent', eventCategory, 'click', eventName])
}

export default {
    apiUrl,
    post,
    getCookie,
    setCookie,
    delCookie,
    getQueryString,
    lineTip,
    baiduPoint,
    paramfactory,
    geturlparam,
    is_baidu
}
